<template>
    <el-form :model="form" label-width="auto" style="max-width: 100%;">
        <!-- 项目名称 -->
        <el-form-item label="项目名称">
            <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="项目目标金额">
            <el-input v-model="form.target" />
        </el-form-item>
        <!-- 图片上传 -->
        <el-form-item label="图片上传">
            <upload-image v-model="form.image" />
        </el-form-item>
        <el-form-item label="项目介绍">
            <el-input v-model="form.desc" type="textarea" />
        </el-form-item>
        <el-form-item class="submit-btn">
            <el-button type="primary" @click="onSubmit">提交</el-button>
            <el-button>取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { reactive } from 'vue'
import { useStore } from 'vuex';
import UploadImage from './UploadImage.vue'
import { watch } from 'vue';

const store = useStore();
const uid=JSON.parse(localStorage.getItem('User')).userid;

const form = reactive({
    name: '',
    image: '',
    desc: '',
    target: 0,
})

// 自定义防抖函数
const debounce = (func, wait) => {
    let timeout = null;
    const debounced = function(...args) {
        const context = this;
        if (timeout) clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
    };
    return debounced;
};
// 使用防抖函数来处理变化，顺便保存在本地
const debouncedUpdate = debounce((newVal, oldVal) => {
    store.commit('CreateProject/updateProjectInfo', {
        uid:uid ,
        name: newVal.name,
        desc: newVal.desc,
        target: newVal.target,
    })
}, 1000)

watch(form, debouncedUpdate, { deep: true, immediate: true })
const onSubmit = () => {
    console.log('submit!')
    store.dispatch('CreateProject/createProject')
}
</script>

<style scoped>
.submit-btn {
    margin-top:5%;
    margin-left: 30%;
}
</style>